/*jslint browser: true, devel: true, bitwise: true, white: true, plusplus: true */
/*global $:true, define:true */

/**
 * @module Core
 */

define(function() {
"use strict";

if (!window.XMLHttpRequest) {
	window.alert('This browser not support ajax');
}

/** Zapewnia obsługe żądań asynchronicznych.
 * @class AJAX
 * @constructor
 */
return {
	
	onSuccess: function(xhr) {
	},
	
	onFailure: function(xhr,options) {
		alert('Failure Request:url: '+options.url+', status: '+xhr.status+', statusText: '+xhr.statusText);
	},
	
	newRequest: function(options) {
		var xhr = new XMLHttpRequest();
		this.setEventListeners(xhr,options);
		return xhr;
	},
	
	setEventListeners: function(xhr, options) {
		var 
			onSuccess = options.onSuccess||this.onSuccess,
			onFailure = options.onFailure||this.onFailure;
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					onSuccess.call(this,xhr,options);
				} else {
					onFailure.call(this,xhr,options);
				}
			} 
		};
	},
	
	get: function(url, params, onSuccess, onFailure,async) {
		//$.get(url,data,onSuccess);
		
		var xhr = this.newRequest({url:url,params:params,onSuccess:onSuccess,onFailure:onFailure});
		params = this.toQueryString(params);
		
		xhr.open('get',((params)? url+'?'+params : url),(async === undefined)?true:async);
		xhr.send();
	},
	
	post: function(url, params, onSuccess, onFailure,async) {
		//$.post(url,data,onSuccess);
		
		var xhr = this.newRequest({url:url,params:params,onSuccess:onSuccess,onFailure:onFailure});
		xhr.open('post',url,(async === undefined)?true:async);
		xhr.send(this.toQueryString(params));
	},
	
	/*getJSON: function(url,onSuccess, onFailure) {
		//$.getJSON(url,onSuccess);
	},
	
	getFile: function(url, onSuccess, onFailure) {
		
	},*/
	
	/**
   * Converting query params to query string 
   * @method toQueryString
   * @param {Object} query params to converting
   * @example 
   * AJAX.toQueryString({a:true,b:null,c:'a table'}); // output: a=true&b=null&c=a%20table
   */
	toQueryString: function(params) {
		if (!params) {
			return null;
		}
		var i = 0, paramName, queryParams = [];
	
		for (paramName in params) {
			if (params.hasOwnProperty(paramName)) {
				queryParams[i++] = this.toQueryPair(paramName,params[paramName]);
			}
		}
		
		return queryParams.join('&');
	},
	
	/**
   * Converting query param to query string pair like key=value
   * @method toQueryPair
   * @param {String} paramName
   * @param value  
   * @example 
   * AJAX.toQueryPair('a',3); // output: a=3
   * AJAX.toQueryPair('b','a table'); // output: b=a%20table
   */
	toQueryPair: function(paramName, value) {
		return encodeURIComponent(paramName) + "=" + encodeURIComponent(value);
	}
};

});
